package strategy;


class SortComparable{
    public Comparable [] sort(Comparable [] arr){
        for (int x = 0; x < arr.length - 1; x++) {//控制外循环次数
            for (int y = 0; y < arr.length - 1 - x; y++) {//-1是为了避免角标越界异常，-x是为了减少外循环次数
                if (arr[y].compareTo(arr[y + 1]) > 0) {//判断两个相邻元素的大小
                    swap(arr, y, y + 1);
                }
            }
        }
        return arr;
    }
    public void swap(Comparable [] arr, int a, int b){
        Comparable temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }
}



abstract class Animal{
    int width = 0;
    int height = 0;

    @Override
    public String toString() {
        return "Animal{" +
                "width=" + width +
                ", height=" + height +
                '}';
    }
}

class Cat extends Animal implements Comparable<Animal>{
    Cat(int w, int h){
        this.width = w;
        this.height = h;
    }
    @Override
    public int compareTo(Animal o) {
        return this.width - o.width > 0 ? 1 : 0;
    }
}

class Dog extends Animal implements Comparable<Animal>{
    Dog(int w, int h){
        this.width = w;
        this.height = h;
    }
    @Override
    public int compareTo(Animal o) {
        return this.height - o.height > 0 ? 1 : 0;
    }
}

public class CompareTo {
    public static void main(String[] args) {

        Comparable [] c = new Comparable[]{new Cat(1,2), new Cat(3,5), new Cat(-1,-2), new Cat(88,-3)};
        Comparable [] d = new Comparable[]{new Dog(1,2), new Dog(3,5), new Dog(-1,-2), new Dog(88,-3)};

        new SortComparable().sort(c);
        new SortComparable().sort(d);

        for(Comparable item:c){
            System.out.println(item);
        }
        System.out.println("===============");
        for (Comparable item:d){
            System.out.println(item);
        }

    }
}
